package com.lenovo.spider.process.downloader;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.lenovo.spider.Context;
import com.lenovo.spider.domain.Request;
import com.lenovo.spider.domain.Response;
import com.lenovo.spider.support.cookie.SpiderCookieJar;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import okhttp3.OkHttpClient;

import java.io.IOException;
import java.net.Proxy;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static com.lenovo.spider.domain.Request.GET;
import static com.lenovo.spider.domain.Request.POST;

/**
 * @author <a href="mailto:liuhan3@lenovo.com">HanL(liuhan3)</a>
 * on 2018/3/27 15:08
 */
@Slf4j
public class HttpDownloader extends Downloader {
    /**
     * 下载器计数
     */
    private final AtomicInteger counter;
    /**
     * 下载器http客户端
     */
    private final OkHttpClient templateClient;

    public HttpDownloader() {
        this.counter = new AtomicInteger(0);
        this.templateClient = new OkHttpClient.Builder()
                .followRedirects(true)
                .cookieJar(Context.getInstance().getCookieJar())
                .connectTimeout(3, TimeUnit.MINUTES)
                .writeTimeout(3, TimeUnit.MINUTES)
                .readTimeout(3, TimeUnit.MINUTES)
                .build();
    }

    @Override
    protected Response doDownload(Request request) throws IOException {
        log.info("下载：{}", request);
//        safeSleep(RandomUtil.randomInt(1000, 5000));
        if (request.getDownloaderType() == Request.DownloaderType.WEBDRIVER) {
            throw new UnsupportedOperationException("不支持的下载器类型");
        }
        val client = this.newClientWithProxy(request.getProxy());
        addCookies(client, request);

        val req = newClientRequest(request);
        val resp = client.newCall(req).execute();
        return convertResponse(request, resp);
    }

    /**
     * 转换响应结果
     *
     * @param request
     * @param resp
     * @return
     * @throws IOException
     */
    private Response convertResponse(Request request, okhttp3.Response resp) throws IOException {
        val response = new Response(resp.code(), resp.request().url().toString(), request);
        response.setContent(Objects.requireNonNull(resp.body()).string());
        return response;
    }

    /**
     * 创建请求
     *
     * @param request
     * @return
     */
    private okhttp3.Request newClientRequest(Request request) {
        val reqBuilder = new okhttp3.Request.Builder();

        val headers = request.getHeaders();
        if (CollUtil.isNotEmpty(headers)) {
            headers.forEach(reqBuilder::addHeader);
        }
        val method = request.getMethod();
        val params = request.getParams();
        val url = request.getUrl();
        if (StrUtil.equalsIgnoreCase(GET, method)) {
            // GET请求
            reqBuilder.url(request.hasParams() ? HttpUtil.urlWithForm(url, params.getBody(), Charset.forName("utf-8"), false) : url).get();
        } else if (StrUtil.equalsIgnoreCase(POST, method)) {
            // POST请求
            reqBuilder.url(url).post(params.toRequestBody());
        } else {
            reqBuilder.url(url);
        }
        return reqBuilder.build();
    }


    /**
     * 创建新的httpclient，并设置proxy
     *
     * @param proxy
     * @return
     */
    private OkHttpClient newClientWithProxy(Proxy proxy) {
        if (proxy == null) {
            return templateClient;
        }
        val clientBuilder = this.templateClient.newBuilder();
        clientBuilder.proxy(proxy);
        return clientBuilder.build();
    }

    /**
     * 添加请求中自定义的cookie
     *
     * @param client
     * @param request
     */
    private void addCookies(OkHttpClient client, Request request) {
        ((SpiderCookieJar) client.cookieJar()).addCustomCookies(request.getUrl(), request.getCookies());
    }
}
